﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AudioManager : MonoBehaviour
{
    //将声音管理器写成单例模式
    public static AudioManager Am;
    //音乐播放器
    public AudioSource MusicPlayer;
    //音效播放器
    public AudioSource SoundPlayer;
    public AudioClip level0;
    public AudioClip level4;
    public AudioClip gameStart;
    
    public int lastLevel;
    // Start is called before the first frame update
    void Start()
    {
        Am = this;
        if (MusicPlayer != null)
        {
            MusicPlayer.Stop();
        }
        if (SoundPlayer != null)
        {
            SoundPlayer.Stop();
        }
        if (GameManager.Instance != null && GameManager.Instance.EventOnGameStart != null)
        {
            GameManager.Instance.EventOnChapterChange -= EventOnChapterChange;
            GameManager.Instance.EventOnChapterChange += EventOnChapterChange;
            GameManager.Instance.EventOnGameStart.RemoveListener(GameStart);
            GameManager.Instance.EventOnGameStart.AddListener(GameStart);
            PlayMusic(-1);
        }
        else
        {
            PlayMusic(-1);

        }
        lastLevel = -1;
    }
    void GameStart(){
        PlayLevel0();
    }
    // Update is called once per frame
    void Update()
    {
    }
    void EventOnChapterChange(int chapter){
        int tempLevel = 0;
        if(chapter > 3){
            tempLevel = 4;
        }
        if(tempLevel == lastLevel){
            return;
        }
        lastLevel = tempLevel;

        if(chapter > 3){
            PlayLevel4();
        }else{
            PlayLevel0();
        }
    }

    // Update is called once per frame
    void PlayLevel0()
    {
        lastLevel = 0;
        PlayMusic(0);
    }
    void PlayLevel4()
    {
        lastLevel = 4;
        PlayMusic(4);
    }
    //播放音乐
    public void PlayMusic(int level)
    {
        if (MusicPlayer.isPlaying)
        {
            MusicPlayer.Stop();
        }
        // AudioClip clip = Resources.Load<AudioClip>(name);

        AudioClip clip = gameStart;
        if (level == -1)
        {
            clip = gameStart;
        }
        else if (level > 3)
        {
            clip = level4;
        }
        else
        {
            clip = level0;
        }
        if (clip != null)
        {
            MusicPlayer.clip = clip;
            MusicPlayer.Play();
        }

    }

    //播放音效
    public void PlaySound(string name)
    {
        AudioClip clip = Resources.Load<AudioClip>(name);
        // AudioClip clip = audios[name];
        if (clip != null)
        {
            SoundPlayer.clip = clip;
            SoundPlayer.PlayOneShot(clip);
        }

    }

}
